package com.pansoft.kline.fragment;

import android.graphics.Color;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.JfResourceUtil;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.google.gson.Gson;
import com.pansoft.kline.adapter.DealBigMonitoringAdapter;
import com.pansoft.kline.adapter.DealRealFundAdapter;
import com.pansoft.kline.base.KlineBaseFragment;
import com.pansoft.kline.formatter.ValueFormatter;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.DealRealFundRemoteModel;
import com.pansoft.kline.model.TableInfo;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.TimeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_FUND_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/10 13:51
 * @desc : 资金fragment
 * @version: 1.0
 */
public class DealRealFundFragment extends KlineBaseFragment implements
        OnChartValueSelectedListener {

    private TextView tv_detail_fund_cap_flow_in;

    private TextView tv_detail_fund_cap_flow_out;
    //成交大单的加载状态
    private TextView tv_deal_larger_monitoring;
    PieChart pieChart;

    LineChart lc_real_time;

    BarChart barChart;
    RecyclerView recycler;

    RecyclerView rv_deal_big_monitoring;
    List<TableInfo> tableInfos = new ArrayList<>();
    List<TableInfo> dealBigMonitoringList = new ArrayList<>();
    private DealRealFundAdapter adapter;
    private DealBigMonitoringAdapter dealBigMonitoringAdapter;

    private String site;
    private String coin;
    private String marketId;
    private ConfigCoinBean coinBean;
    private ConfigMarketBean marketBean;
    private ConfigSiteBean siteBean;

    public static DealRealFundFragment newInstance(String marketId) {
        Bundle args = new Bundle();
        DealRealFundFragment fragment = new DealRealFundFragment();
        //当前coin的site，coin的name
        args.putString("marketId", marketId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void refreshPage() {

    }

    @Override
    public void requestData() {
        initData();
    }

    @Override
    protected void initArgs(Bundle bundle) {
        super.initArgs(bundle);
        marketId = bundle.getString("marketId");
        marketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(marketId);
        coinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(marketBean.getCoin());
        siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(marketBean.getSite());
    }

    @Override
    protected void initData() {
        super.initData();
        requestRemoteFundData();
    }

    private void requestRemoteFundData() {

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("site", siteBean.getUniqueKey());
        hashMap.put("coin", coinBean.getName());
        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MARKET_DETAIL_FUND_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    DealRealFundRemoteModel dealRealFundRemoteModel = new Gson().fromJson(result, DealRealFundRemoteModel.class);
                    if (dealRealFundRemoteModel.getCode() != 0) {
//                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);

                        return;
                    }
                    disposeFundData(dealRealFundRemoteModel);
                    initBarChart(result);
                    //处理成交大单监控的列表
                    disposeLargeOrders(dealRealFundRemoteModel);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                    //显示暂无数据
//                    View noDataView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_chart_no_data,null);
//                    dealBigMonitoringAdapter.setEmptyView(noDataView);
                    tv_deal_larger_monitoring.setVisibility(View.VISIBLE);
                    tv_deal_larger_monitoring.setText(R.string.kline_detail_no_data);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
            }
        });
    }

    /**
     * 处理请求下来的数据
     *
     * @param dealRealFundRemoteModel
     */
    private void disposeFundData(DealRealFundRemoteModel dealRealFundRemoteModel) {
        DealRealFundRemoteModel.DataBean.FundChartBean fundChartBean = dealRealFundRemoteModel.getData().getFund_chart();
        if (fundChartBean == null) {
            return;
        }
        double income = fundChartBean.getIncomes() / (fundChartBean.getIncomes() + fundChartBean.getOutputs()) * 100;
        double output = fundChartBean.getOutputs() / (fundChartBean.getIncomes() + fundChartBean.getOutputs()) * 100;
        //设置圆形数据
        setPieChartData(income, output);

        tv_detail_fund_cap_flow_in.setText(MarketNumberUtils.amountConversion(MarketNumberUtils
                .getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, fundChartBean.getIncomes())));

        tv_detail_fund_cap_flow_out.setText(MarketNumberUtils.amountConversion(MarketNumberUtils
                .getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, fundChartBean.getOutputs())));
        initLineChartTime();
        setLineChartTimeData(dealRealFundRemoteModel.getData().getTrend_records());
        //24小时内的资金流向趋势
        dispose24HourDealData(dealRealFundRemoteModel);

    }

    /**
     * 处理成交大单监控列表的数据
     *
     * @param dealRealFundRemoteModel
     */
    private void disposeLargeOrders(DealRealFundRemoteModel dealRealFundRemoteModel) {
        dealBigMonitoringList.clear();
        List<DealRealFundRemoteModel.DataBean.LargeOrdersBean> largeOrdersBeans = dealRealFundRemoteModel.getData().getLarge_orders();
        if (largeOrdersBeans != null && largeOrdersBeans.size() > 0) {
            tv_deal_larger_monitoring.setVisibility(View.GONE);
            for (int i = 0; i < largeOrdersBeans.size(); i++) {
                DealRealFundRemoteModel.DataBean.LargeOrdersBean largeOrdersBean = largeOrdersBeans.get(i);
                TableInfo tableInfo = new TableInfo();
                tableInfo.setTime(largeOrdersBean.getTime());
                tableInfo.setBuy(MarketNumberUtils.amountConversion(
                        TCMathUtil.mul(largeOrdersBean.getAmount(), getFormatCurrencyNumber(largeOrdersBean.getUsd_price()))));
                tableInfo.setSale(MarketNumberUtils.amountConversion(largeOrdersBean.getAmount()));
                tableInfo.setFlowInto(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(largeOrdersBean.getUsd_price())));
                dealBigMonitoringList.add(tableInfo);
            }
            TableInfo tableInfo2 = new TableInfo();
            tableInfo2.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_time));
            tableInfo2.setBuy(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_amount_of_money,KLineUtil.getCurrencySymbol(wantCurrency)));
            tableInfo2.setSale(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_number,coinBean.getName()));
            tableInfo2.setFlowInto(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_price,KLineUtil.getCurrencySymbol(wantCurrency)));
            dealBigMonitoringList.add(0, tableInfo2);
            dealBigMonitoringAdapter.notifyDataSetChanged();
        } else {
            tv_deal_larger_monitoring.setVisibility(View.VISIBLE);
            tv_deal_larger_monitoring.setText(R.string.kline_detail_no_data);
            //显示暂无数据
//            View noDataView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_chart_no_data,null);
//            dealBigMonitoringAdapter.setEmptyView(noDataView);
        }

    }

    /**
     * 处理24小时内的资金流向趋势
     *
     * @param dealRealFundRemoteModel
     */
    private void dispose24HourDealData(DealRealFundRemoteModel dealRealFundRemoteModel) {
        tableInfos.clear();
        DealRealFundRemoteModel.DataBean.TableRecordsBean tableRecordsBean = dealRealFundRemoteModel.getData().getTable_records();
        List<DealRealFundRemoteModel.DataBean.Recent1hourMinutesRecordsBean> recent1hourMinutesRecordsBean = dealRealFundRemoteModel.getData().getRecent_1hour_minutes_records();
        initTableData();
        //今日数据
        if (tableRecordsBean != null) {
            DealRealFundRemoteModel.DataBean.TableRecordsBean.TodayBean todayBean = tableRecordsBean.getToday();
            TableInfo todayTable = new TableInfo();
            todayTable.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_today));
            todayTable.setBuy(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(todayBean.getIncomes())));
            todayTable.setSale(MarketNumberUtils.amountConversion((getFormatCurrencyNumber(todayBean.getOutputs()))));
            todayTable.setFlowInto(MarketNumberUtils.amountConversion((getFormatCurrencyNumber(todayBean.getIncomes() - todayBean.getOutputs()))));
            tableInfos.add(todayTable);
        }
        //3分钟内数据和 10分钟数据
        double threeBuy = 0.00;
        double threeSell = 0.00;
        double threeTotal = 0.00;
        double tenBuy = 0.00;
        double tenSell = 0.00;
        double tenTotal = 0.00;
        double hourBuy = 0.00;
        double hourSell = 0.00;
        double hourTotal = 0.00;
        if (recent1hourMinutesRecordsBean != null && recent1hourMinutesRecordsBean.size() > 0) {
            for (int i = 0; i < recent1hourMinutesRecordsBean.size(); i++) {
                DealRealFundRemoteModel.DataBean.Recent1hourMinutesRecordsBean recent1hourMinutesRecordsBean1 = recent1hourMinutesRecordsBean.get(i);
                long time = TimeUtils.date2Millis(TimeUtils.string2Date(recent1hourMinutesRecordsBean1.getTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm")));
                //如果time 大于 3分钟
                if (time > (System.currentTimeMillis() - (3 * 60 * 1000))) {
                    threeBuy = threeBuy + recent1hourMinutesRecordsBean1.getIncomes();
                    threeSell = threeSell + recent1hourMinutesRecordsBean1.getOutputs();
                    threeTotal = threeTotal + recent1hourMinutesRecordsBean1.getTotal_fund();
                }
                //如果time 大于 10分钟
                if (time > (System.currentTimeMillis() - (10 * 60 * 1000))) {
                    tenBuy = tenBuy + recent1hourMinutesRecordsBean1.getIncomes();
                    tenSell = tenSell + recent1hourMinutesRecordsBean1.getOutputs();
                    tenTotal = tenTotal + recent1hourMinutesRecordsBean1.getTotal_fund();
                }
                //如果time 大于一小时
                if (time > (System.currentTimeMillis() - (60 * 60 * 1000))) {
                    hourBuy = hourBuy + recent1hourMinutesRecordsBean1.getIncomes();
                    hourSell = hourSell + recent1hourMinutesRecordsBean1.getOutputs();
                    hourTotal = hourTotal + recent1hourMinutesRecordsBean1.getTotal_fund();
                }
            }
            //添加3分钟数据
            TableInfo threeTable = new TableInfo();
            threeTable.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_three_minute));
            threeTable.setBuy(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(threeBuy)));
            threeTable.setSale(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(threeSell)));
            threeTable.setFlowInto(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(threeTotal)));
            tableInfos.add(threeTable);
            //添加10分钟数据
            TableInfo tenTable = new TableInfo();
            tenTable.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_ten_minute));
            tenTable.setBuy(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(tenBuy)));
            tenTable.setSale(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(tenSell)));
            tenTable.setFlowInto(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(tenTotal)));
            tableInfos.add(tenTable);
            //添加一小时数据
            TableInfo hourTable = new TableInfo();
            hourTable.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_one_hour));
            hourTable.setBuy(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(hourBuy)));
            hourTable.setSale(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(hourSell)));
            hourTable.setFlowInto(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(hourTotal)));
            tableInfos.add(hourTable);
            //处理24小时数据
            DealRealFundRemoteModel.DataBean.TableRecordsBean._$24hoursBean hoursBean = dealRealFundRemoteModel.getData().getTable_records().get_$24hours();
            TableInfo todayTable = new TableInfo();
            todayTable.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_24_hour));
            todayTable.setBuy(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(hoursBean.getIncomes())));
            todayTable.setSale(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(hoursBean.getOutputs())));
            todayTable.setFlowInto(MarketNumberUtils.amountConversion(getFormatCurrencyNumber(hoursBean.getIncomes() - hoursBean.getOutputs())));
//            if(hoursBean.getIncomes()-hoursBean.getOutputs()>0){
//                todayTable.
//            }
            tableInfos.add(todayTable);

            adapter.notifyDataSetChanged();
        }


    }


    public double getFormatCurrencyNumber(double number) {
        return MarketNumberUtils
                .getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, number);
    }

    /**
     * 模拟表格数据
     */
    private void initTableData() {
        TableInfo tableInfo1 = new TableInfo();
        tableInfo1.setTime(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_time));
        tableInfo1.setBuy(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_buy));
        tableInfo1.setSale(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_sale));
        tableInfo1.setFlowInto(_mActivity.getResources().getString(R.string.chart_kline_detail_fund_table_flow_in));
        tableInfos.add(0, tableInfo1);


    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        ((TextView)root.findViewById(R.id.tv_fund_deal_unit)).setText(String
            .format(getString(R.string.kline_detail_fund_cap_unit),
                    CurrencyAndBourseManager.getCurrencyUnitCode()));
        tv_detail_fund_cap_flow_in = root.findViewById(R.id.tv_detail_fund_cap_flow_in);
        tv_detail_fund_cap_flow_out = root.findViewById(R.id.tv_detail_fund_cap_flow_out);
        tv_deal_larger_monitoring = root.findViewById(R.id.tv_deal_larger_monitoring);
        pieChart = root.findViewById(R.id.pieChart);
        lc_real_time = root.findViewById(R.id.lc_real_time);
        barChart = root.findViewById(R.id.barChart);
        recycler = root.findViewById(R.id.recycler);
        rv_deal_big_monitoring = root.findViewById(R.id.rv_deal_big_monitoring);

        recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new DealRealFundAdapter(R.layout.item_deal_real_fund_table, tableInfos);
        recycler.setAdapter(adapter);
        recycler.setNestedScrollingEnabled(false);

        rv_deal_big_monitoring.setLayoutManager(new LinearLayoutManager(getActivity()));
        dealBigMonitoringAdapter = new DealBigMonitoringAdapter(R.layout.item_deal_big_monitoring_table, dealBigMonitoringList);
        rv_deal_big_monitoring.setAdapter(dealBigMonitoringAdapter);
        rv_deal_big_monitoring.setNestedScrollingEnabled(false);
        //设置边距
        pieChart.setExtraOffsets(20.f, 10.f, 20.f, 10.f);
        pieChart.getDescription().setEnabled(false);
        pieChart.setDrawHoleEnabled(true);
        pieChart.setTouchEnabled(false);
        pieChart.setTransparentCircleAlpha(110);
        pieChart.setHoleColor(JfResourceUtil.getSkinColor(R.color.frame_white_background_color));
        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(0f);
        pieChart.setNoDataText(getResources().getString(R.string.kline_detail_no_data));
        //成交分布
        pieChart.setCenterText(getResources().getString(R.string.chart_kline_detail_fund_transaction_distribution));
        pieChart.setCenterTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        pieChart.setDrawCenterText(true);
        pieChart.setNoDataTextColor(JfResourceUtil.getSkinColor(R.color.main_text_color));
        pieChart.setRotationAngle(90);
        // enable rotation of the chart by touch
        pieChart.setRotationEnabled(false);
        pieChart.setHighlightPerTapEnabled(false);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
        pieChart.setOnChartValueSelectedListener(this);


        pieChart.animateY(1400, Easing.EaseInOutQuad);
        // chart.spin(2000, 0, 360);

        Legend l = pieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setEnabled(false);


    }


    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_deal_real_fund;
    }


    /**
     * 设置饼形图的数据
     *
     * @param incomes
     * @param outputs
     */
    private void setPieChartData(double incomes, double outputs) {

        ArrayList<PieEntry> entries = new ArrayList<>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
//        entries.add(new PieEntry(Float.valueOf(MarketNumberUtils
//                .amountConversion(MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, incomes)))));
//        entries.add(new PieEntry(Float.valueOf(MarketNumberUtils
//                .amountConversion(MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, outputs)))));
        //四舍五入保留两位小数的百分比
        entries.add(new PieEntry(Float.valueOf(String.valueOf(MarketNumberUtils.formatNumber(incomes, 2, true)))));
        entries.add(new PieEntry(Float.valueOf(String.valueOf(MarketNumberUtils.formatNumber(outputs, 2, true)))));
        PieDataSet dataSet = new PieDataSet(entries, "");
//        dataSet.setSliceSpace(3f);
//        dataSet.setSelectionShift(5f);
        // add a lot of colors

        ArrayList<Integer> colors = new ArrayList<>();
        ArrayList<Integer> valueColors = new ArrayList<>();

        if (incomes == 0) {
            colors.add(getResources().getColor(R.color.trans));
            valueColors.add(getResources().getColor(R.color.trans));

        } else {
            colors.add(getResources().getColor(R.color.main_color_green));
            valueColors.add(JfResourceUtil.getSkinColor(R.color.chart_main_white_or_black));
        }
        if (outputs == 0) {
            colors.add(getResources().getColor(R.color.trans));
            valueColors.add(getResources().getColor(R.color.trans));
        } else {
            colors.add(getResources().getColor(R.color.main_color_red));
            valueColors.add(JfResourceUtil.getSkinColor(R.color.chart_main_white_or_black));
        }


        dataSet.setColors(colors);
        dataSet.setSelectionShift(0f);
//        dataSet.setValueLinePart1OffsetPercentage(80.f);

        dataSet.setValueLinePart1Length(0.4f);
        dataSet.setValueLinePart2Length(0.4f);
        dataSet.setUsingSliceColorAsValueLineColor(true);
        //dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
        dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(13f);
        data.setValueTextColors(valueColors);
//        data.setValueTypeface(tf);
        pieChart.setData(data);
        // undo all highlights
        pieChart.highlightValues(null);
        pieChart.invalidate();

    }


    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    /**
     * 资金流向趋势图
     */
    private void initLineChartTime() {
        // no description text
        lc_real_time.getDescription().setEnabled(false);

        // enable touch gestures
        lc_real_time.setTouchEnabled(false);

        lc_real_time.setBorderColor(_mActivity.getResources().getColor(R.color.trans_gray));
        lc_real_time.setBorderWidth(SizeUtils.dp2px(0.1f));
        lc_real_time.setDrawBorders(false);
        lc_real_time.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
//        lc_real_time.setNoDataTextColor(getResources().getColor(R.color.white_alpha_160));
        // enable scaling and dragging
        lc_real_time.setDragEnabled(true);
        lc_real_time.setScaleEnabled(true);
        lc_real_time.setDrawGridBackground(false);
        lc_real_time.setHighlightPerDragEnabled(true);
        lc_real_time.setNoDataTextColor(getResources().getColor(R.color.main_text_color));
        lc_real_time.setNoDataText(getResources().getString(R.string.kline_detail_no_data));
        //控制上下左右坐标轴显示的距离

//        lc_real_time.setClipValuesToContent(true);
        // get the legend (only possible after setting data)
        Legend l = lc_real_time.getLegend();
        l.setEnabled(false);

        XAxis xAxis = lc_real_time.getXAxis();
        //设置x轴的显示位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(10f);
        //是否绘制轴线
        xAxis.setDrawAxisLine(false);
        //设置x轴上每个点对应的线
        xAxis.setDrawGridLines(true);
        xAxis.setGridColor(getResources().getColor(R.color.divide_line_color));
        xAxis.setTextColor(getResources().getColor(R.color.main_text_color));

//        xAxis.setAvoidFirstLastClipping(true);
        //默认为true   设置为false网格线在数据之上
//        xAxis.setDrawGridLinesBehindData(false);
//        xAxis.setGranularity(1f);
//        xAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴刻度数量
        xAxis.setLabelCount(3, true);
        xAxis.setAvoidFirstLastClipping(true);
        xAxis.setValueFormatter(new ValueFormatter() {

            private final SimpleDateFormat mFormat = new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA);

            @Override
            public String getFormattedValue(float value) {
//                LogUtils.e("getFormattedValue---》"+value);
                long millis = TimeUnit.HOURS.toMillis((long) value);

                if (Math.abs((int) value) < trendRecordsBeanList.size()) {
                    return mFormat.format(new Date(TimeUtils.date2Millis(TimeUtils.string2Date(trendRecordsBeanList.get(Math.abs((int) value)).getTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm")))));
                }
                return "";
            }


        });
        YAxis leftAxis = lc_real_time.getAxisLeft();
        leftAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setDrawGridLines(true);
        leftAxis.setGridColor(getResources().getColor(R.color.divide_line_color));
        leftAxis.setGranularityEnabled(true);
//        leftAxis.setAxisMinimum(0f);
//        leftAxis.setAxisMaximum(170f);
//        leftAxis.setYOffset(-15f);
        leftAxis.setLabelCount(4, true);
        leftAxis.setAxisLineColor(getResources().getColor(R.color.divide_line_color));
        leftAxis.setTextColor(getResources().getColor(R.color.main_text_color));

        YAxis rightAxis = lc_real_time.getAxisRight();
        rightAxis.setEnabled(false);
    }

    private List<DealRealFundRemoteModel.DataBean.TrendRecordsBean> trendRecordsBeanList = new ArrayList<>();

    /**
     * 设置资金流向趋势图的数据
     *
     * @param trendRecordsBeans
     */
    private void setLineChartTimeData(List<DealRealFundRemoteModel.DataBean.TrendRecordsBean> trendRecordsBeans) {
        trendRecordsBeanList.addAll(trendRecordsBeans);

        ArrayList<Entry> values = new ArrayList<>();

        // increment by 1 hour
        for (int i = 0; i < trendRecordsBeans.size(); i++) {
            float x = TimeUnit.MILLISECONDS.toHours(TimeUtils.date2Millis(TimeUtils.string2Date(trendRecordsBeans.get(i).getTime(), new SimpleDateFormat("yyyy-MM-dd HH:mm"))));
            float y = (float) getFormatCurrencyNumber(trendRecordsBeans.get(i).getTotal_fund());
            values.add(new Entry(i, y)); // add one entry per hour
        }

        // create a dataset and give it a type
        LineDataSet set1 = new LineDataSet(values, "");
//        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//        set1.setColor(getResources().getColor(R.color.ma5));
        set1.setColor(getResources().getColor(R.color.main_color_red));

        set1.setValueTextColor(getResources().getColor(R.color.main_text_color));
        set1.setLineWidth(1.5f);
        set1.setDrawCircles(false);
        set1.setDrawValues(false);
        set1.setFillAlpha(65);
        set1.setFillColor(getResources().getColor(R.color.main_text_color));
//        set1.setHighLightColor(getResources().getColor(R.color.main_text_color));
        set1.setDrawCircleHole(false);
        // create a data object with the data sets
        LineData data = new LineData(set1);
        data.setValueTextColor(Color.WHITE);
        data.setValueTextSize(9f);

        // set data
        lc_real_time.setData(data);
        lc_real_time.invalidate();
    }

    /**
     * 初始化近五日资金净流入
     */
    private void initBarChart(String result) {
//        barChart.setExtraTopOffset(0f);
//        barChart.setExtraBottomOffset(0f);
//        barChart.setExtraLeftOffset(-30f);
//        barChart.setExtraRightOffset(-30f);
        barChart.setTouchEnabled(false);
        barChart.setExtraBottomOffset(5f);
        barChart.setExtraLeftOffset(10f);
        barChart.setExtraRightOffset(10f);
        barChart.setFitBars(true);//使两侧的柱图完全显示
        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);
        barChart.setNoDataTextColor(getResources().getColor(R.color.main_text_color));
        barChart.setNoDataText(getResources().getString(R.string.kline_detail_no_data));
        barChart.getDescription().setEnabled(false);
        // scaling can now only be done on x- and y-axis separately
        barChart.setPinchZoom(false);
        barChart.setScaleEnabled(false);
        barChart.setDrawGridBackground(false);
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setTextColor(Color.LTGRAY);
        xAxis.setTextSize(12f);
        xAxis.setLabelCount(5);
        xAxis.setGranularity(1f);
        xAxis.setTextColor(getResources().getColor(R.color.main_text_color));
        YAxis left = barChart.getAxisLeft();
        left.setDrawLabels(false);
        left.setSpaceTop(10f);
        left.setSpaceBottom(10f);
        left.setDrawAxisLine(false);
        left.setDrawGridLines(false);
        left.setDrawZeroLine(true); // draw a zero line
        left.setZeroLineColor(Color.GRAY);
//        left.setZeroLineWidth(0.7f);
        barChart.getAxisRight().setEnabled(false);
        barChart.getLegend().setEnabled(false);


        final List<Data> data = disposeBarChartData(result);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                String result = data.get(Math.min(Math.max((int) value, 0), data.size() - 1)).xAxisValue;
                return result;
            }
        });
        setData(data);
    }

    private List<Data> disposeBarChartData(String result) {
        // THIS IS THE ORIGINAL DATA YOU WANT TO PLOT
        final List<Data> data = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject days = jsonObject.optJSONObject("data").optJSONObject("day_records");
            int i = 0;
            if (days != null) {
                Iterator iterator = days.keys();
                while (iterator.hasNext()) {
                    i++;
                    String key = iterator.next().toString();
                    data.add(new Data(i - 1, (float) days.optDouble(key), TimeUtils.date2String(TimeUtils.string2Date(key, new SimpleDateFormat("yyyy-MM-dd")), new SimpleDateFormat("MM-dd"))));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return data;

    }

    /**
     * 设置近五日资金净流入图的数据
     *
     * @param dataList
     */
    private void setData(List<Data> dataList) {

        ArrayList<BarEntry> values = new ArrayList<>();
        List<Integer> colors = new ArrayList<>();

        int green = getResources().getColor(R.color.main_color_green);
        int red = getResources().getColor(R.color.main_color_red);

        for (int i = 0; i < dataList.size(); i++) {

            Data d = dataList.get(i);
            BarEntry entry = new BarEntry(d.xValue, d.yValue);
            values.add(entry);

            // specific colors
            if (d.yValue >= 0) {
                colors.add(green);
            } else {
                colors.add(red);
            }
        }

        BarDataSet set;

        if (barChart.getData() != null &&
                barChart.getData().getDataSetCount() > 0) {
            set = (BarDataSet) barChart.getData().getDataSetByIndex(0);
            set.setValues(values);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            set = new BarDataSet(values, "Values");
            set.setColors(colors);
            set.setValueTextColors(colors);
            BarData data = new BarData(set);
            data.setValueTextSize(12f);
            data.setValueFormatter(new Formatter());
            //柱体宽度 这里设为0.6f那么柱体之间的间距就为0.4f
            data.setBarWidth(0.5f);
            barChart.setData(data);
            barChart.invalidate();
        }
    }

    /**
     * Demo class representing data.
     */
    private class Data {

        final String xAxisValue;
        final float yValue;
        final float xValue;

        Data(float xValue, float yValue, String xAxisValue) {
            this.xAxisValue = xAxisValue;
            this.yValue = yValue;
            this.xValue = xValue;
        }
    }

    private class Formatter extends ValueFormatter {

//        private final DecimalFormat mFormat;
//
//        Formatter() {
//            mFormat = new DecimalFormat("######.0");
//        }

        @Override
        public String getFormattedValue(float value) {
            return MarketNumberUtils.amountConversion(getFormatCurrencyNumber(value));
        }
    }
}
